package com.linyaonan.com.nio.channel;

import lombok.Cleanup;
import lombok.SneakyThrows;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author: Lin
 * @date: 2020/11/7
 */
public class ChannelTransfer {

    @SneakyThrows
    public static void main(String[] args) {

        @Cleanup FileChannel readChannel = FileChannel.open(Paths.get("hello.txt"), StandardOpenOption.READ);
        @Cleanup FileChannel writeChannel = FileChannel.open(Paths.get("save.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        long start = System.currentTimeMillis();

        for (int i = 5000000; i > 0; i--) {
            // 6642
//            transferSave(readChannel, writeChannel);
            // 10167
            bufferSave(readChannel, writeChannel);
        }

        long end = System.currentTimeMillis();

        System.out.println("总共花费 = " + (end - start));
    }

    @SneakyThrows
    private static void bufferSave(FileChannel readChannel, FileChannel writeChannel) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (readChannel.read(buffer) != -1) {
            buffer.flip();
            writeChannel.write(buffer);
            buffer.clear();
        }
    }

    @SneakyThrows
    private static void transferSave(FileChannel readChannel, FileChannel writeChannel) {
        // 底层使用的零拷贝技术
        readChannel.transferTo(0, readChannel.position(), writeChannel);
    }

}
